#include "LuaUtil.h"

template<> void toLua(lua_State* L, const bool& arg) {
	lua_pushboolean(L, arg ? 1 : 0);
}

template<> void toLua(lua_State* L, const double& arg) {
	lua_pushnumber(L, arg);
}

template<> void toLua(lua_State* L, const int& arg) {
	lua_pushnumber(L, arg);
}

template<> void toLua(lua_State* L, const std::string& arg) {
	lua_pushstring(L, arg.c_str());
}
void toLua(lua_State* L, const char * arg) {
	lua_pushstring(L, arg);
}

void toLua(lua_State* L, void* ptr) {
	lua_pushlightuserdata(L, ptr);
}

template<> bool fromLua(lua_State* L, int index, bool& ret) {
	if (lua_isboolean(L, index)) {
		ret = lua_toboolean(L, index) != 0;
		return true;
	}

	return false;
}

template<> bool fromLua(lua_State* L, int index, double& ret) {
	if (lua_isnumber(L, index)) {
		ret = lua_tonumber(L, index);
		return true;
	}

	return false;
}

template<> bool fromLua(lua_State* L, int index, int& ret) {
	if (lua_isnumber(L, index)) {
		ret = (int) lua_tonumber(L, index);
		//fprintf(stderr,"%d",ret);
		return true;
	}

	return false;
}

template<> bool fromLua(lua_State* L, int index, std::string& ret) {
	if (lua_isstring(L, index)) {
		ret = lua_tostring(L, index);
		return true;
	}

	return false;
}

bool fromLuaChar(lua_State* L, int index, const char* key, char* ret) {
	// stack: table
	LuaStackChecker sc(L, __FILE__, __LINE__);
	lua_getfield(L, index ? index : LUA_GLOBALSINDEX, key); // stack: table value
	bool res = true;// = fromLua(L, -1, ret);
	if (lua_isstring(L, index)) {
		strcpy(ret, lua_tostring(L, index));
		// ret[strlen(lua_tostring(L, index))]="\0";
		//fprintf(stderr,"%s",ret);
	} else
		res = false;
	lua_pop(L, 1); // stack: table

	return ret;
}
